package com.daokin.filter;

import com.daokin.constant.SystemConstant;
import com.daokin.dto.User;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 *
 * User Admin filtering
 *
 * @author Herbert
 *
 */
@Component("daokinFilter")
public class DaoKinFilter implements Filter {

    protected final Logger logger = Logger.getLogger(this.getClass());

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest,
            ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User currentUser = (User) request.getSession().getAttribute(
                SystemConstant.SESSION_USER_KEY);
        if (currentUser == null) {
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + path;
            response.sendRedirect(basePath + "/login.htm");
        } else {
            chain.doFilter(request, response);
        }
//            chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}
